package com.shengdong.water.code.base

import android.util.Log
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.shengdong.water.base.BaseVMActivity
import com.shengdong.water.base.BaseViewModel
import com.shengdong.water.base.RefreshLoadStatus
import kotlinx.coroutines.launch

abstract class BaseRefreshActivity<T,VB : ViewDataBinding,VM : BaseViewModel> : BaseVMActivity<VB,VM>() {

    protected var currentPage = 1

    protected val pageSize = 10

    private var refreshLayout: SmartRefreshLayout? = null
    private  var recyclerView: RecyclerView? = null
    protected val baseRecyclerAdapter: BaseRecyclerAdapter< T, *> by lazy { getAdapter() }

    override fun initViews() {
        super.initViews()
        refreshLayout = getSmartRefreshLayout()
        initRefreshLayout()
        recyclerView = getRecyclerView()

        recyclerView?.layoutManager = LinearLayoutManager(this)
        recyclerView?.adapter = baseRecyclerAdapter
    }


    abstract fun getRecyclerView(): RecyclerView

    open fun getSmartRefreshLayout(): SmartRefreshLayout? {
        return refreshLayout
    }

    abstract fun getAdapter(): BaseRecyclerAdapter<T, *>


    private fun initRefreshLayout() {
        refreshLayout.apply {
            refreshLayout?.setOnRefreshListener {
                Log.e("下拉刷新", "1111111")
                currentPage = 1
                loadData()
            }
            refreshLayout?.setOnLoadMoreListener {
                currentPage++
                loadData()
            }
        }



    }

    /**

     * 加载数据的抽象方法，子类必须实现

     */

    abstract fun loadData()

    /**

     * 结束刷新和加载更多

     * @param success 是否成功

     * @param totalPages 总页数

     */

    protected fun finishRefreshAndLoadMore(success: Boolean, totalPages: Int) {
        Log.e("下拉刷新finishRefreshAndLoadMore",""+success)
        refreshLayout?.run {
            Log.e("下拉刷新isRefreshing",""+isRefreshing)
            if (isRefreshing) {
                finishRefresh(success)
            }

            if (isLoading) {
                finishLoadMore(success)
            }
            setNoMoreData(currentPage >= totalPages)

        }


    }



    /**

     * 处理列表数据

     */

    protected fun handleData(result: List<T>) {

        if(currentPage == 1){
            baseRecyclerAdapter.setItems(result)
        } else {
            baseRecyclerAdapter.addItems(result)
        }

    }

    /**

     * 重置页码

     */


    override fun observeData() {
        super.observeData()
        // 观察刷新/加载状态
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.refreshLoadStatus.collect { status ->
                    when (status) {
                        is RefreshLoadStatus.Success -> {
                            // 使用后台返回的 total 值
                            finishRefreshAndLoadMore(true, status.total)
                        }
                        is RefreshLoadStatus.Error -> {
                            finishRefreshAndLoadMore(false, 0)
                            if ( currentPage > 1) {
                                currentPage--
                            }
                        }

                        else -> {}
                    }
                }
            }
        }
    }
}